"""
File Name: Pycharm
Description:   job 获取任务
Author: Panwj
Date: 2025/9/9 20:03
"""
import datetime
import json

from flask import Blueprint, request, jsonify

from form.job import JobForm

from utils.redis_util import RedisUtil


bp = Blueprint('job_task_service', __name__, url_prefix='/job/api/v1/task')

JOB_QUEUE_NAME = "Job:%s:queue"

redis_client = RedisUtil().create_redis_connection()

@bp.route("commit_job", methods=['POST', 'GET'])
def commit_job():
    """提交任务"""

    request_method = request.method
    if request_method == 'POST':
        job_from = JobForm(request.json)
        if job_from.validate():
            job_id = __commit_job(**request.json)
            return jsonify({'code': 200, 'msg': '下发任务成功！', 'data': {'job_id': job_id}})
        return jsonify({'code': 500, 'msg': job_from.errors})
    else:
        job_from = JobForm(request.args)
        if job_from.validate():
            job_id = __commit_job(**request.args)
            return jsonify({'code': 200, 'msg': '下发任务成功！', 'data': {'job_id': job_id}})
        return jsonify({'code': 500, 'msg': job_from.errors})


@bp.route('get_job', methods=['GET'])
def get_job():
    site_name = request.args.get('site_name')
    if not site_name:
        return jsonify({'code': 500, 'msg': "site_name can't be empty"})
    job_queue_name = JOB_QUEUE_NAME % site_name.lower()
    job_info = redis_client.rpop(job_queue_name)
    if job_info:
        return jsonify({'code': 200, 'msg': "get job is success!", 'data': job_info})
    else:
        return jsonify({'code': 404, 'msg': "job is empty"})

def random_job_id(site_name, action):
    dt = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    return f'Job-{site_name.lower()}-{action.lower()}-{dt}'


def __commit_job(**kwargs):
    site_name = kwargs['site_name']
    action = kwargs['action_type']
    job_queue_name = JOB_QUEUE_NAME % site_name.lower()
    job_id = random_job_id(site_name, action)
    job_info = {
        'job_id': job_id,
        'action': action,
        'url': kwargs['url'],
        'comment_content': kwargs.get('comment_content'),
        'by_comment_content': kwargs.get('by_comment_content'),
        'site_name': site_name
    }
    redis_client.lpush(job_queue_name, json.dumps(job_info))
    return job_id
